<template>
  <el-dialog
      v-model="dialogVisible"
      :title="title"
      width="900px"
      :close-on-click-modal="false"
      destroy-on-close
  >
    <!-- 模式选择 -->
    <div class="mode-selector mb-4" style="text-align:center">
      <el-radio-group v-model="configMode" @change="handleModeChange">
        <el-radio-button label="single">单数字人模式</el-radio-button>
        <el-radio-button label="multiple">多数字人模式</el-radio-button>
      </el-radio-group>
      <el-tooltip content="单数字人模式：整篇文章由一个数字人生成；多数字人模式：文章可由多个数字人分段生成或者一篇文章对应一个数字人" placement="top">
        <el-icon class="ml-2"><InfoFilled /></el-icon>
      </el-tooltip>
    </div>

    <!-- 单数字人模式 -->
    <template v-if="configMode === 'single'">
      <el-form
          ref="singleFormRef"
          :model="singleConfig"
          :rules="rules"
          label-width="100px"
      >
        <!-- 现有的单数字人配置表单 -->
        <el-form-item label="配置名称" prop="name">
          <el-input v-model="singleConfig.name" placeholder="请输入配置名称" />
        </el-form-item>

        <!-- 虚拟人物选择 -->
        <el-form-item
            label="虚拟人物"
            prop="avatarId"
            :rules="[{ required: true, message: '请选择虚拟人物' }]"
        >
          <div class="select-preview">
            <!-- 现有的人物选择UI -->
            <div v-if="currentAvatar" class="preview-content">
              <el-image
                  :src="currentAvatar.previewImageUrl"
                  class="preview-image"
                  fit="cover"
              >
                <template #error>
                  <div class="image-placeholder">
                    <el-icon><Avatar /></el-icon>
                  </div>
                </template>
              </el-image>
              <div class="preview-info">
                <span>{{ currentAvatar.avatarName }}</span>
                <el-space>
                  <el-tag size="small" :type="getGenderType(currentAvatar.gender)">
                    {{ getGenderLabel(currentAvatar.gender) }}
                  </el-tag>
                  <el-tag size="small" :type="'danger'">
                    {{currentAvatar.premium === true ? '高级版' : '基础版'}}
                  </el-tag>
                </el-space>
              </div>
              <div class="avatar-actions" style="text-align: center">
                <el-button
                    type="primary"
                    link
                    size="small"
                    @click="handlePreview(currentAvatar)"
                >
                  <el-icon><VideoPlay /></el-icon>预览
                </el-button>
              </div>
            </div>
            <el-button @click="showAvatarDialog = true">
              {{ currentAvatar ? '更换' : '选择' }}虚拟人物
            </el-button>
          </div>
        </el-form-item>

        <!-- 人物配置 -->
        <el-form-item label="人物配置">
          <el-collapse>
            <el-collapse-item title="详细配置">
              <div class="avatar-config-form">
                <!-- 现有的人物配置UI -->
                <div class="config-row">
                  <span class="config-label">水平偏移 (X):</span>
                  <el-slider
                      v-model="singleConfig.xOffset"
                      :min="-1"
                      :max="1"
                      :step="0.05"
                      show-input
                      :format-tooltip="value => value.toFixed(2)"
                  />
                </div>
                <div class="config-row">
                  <span class="config-label">垂直偏移 (Y):</span>
                  <el-slider
                      v-model="singleConfig.yOffset"
                      :min="-1"
                      :max="1"
                      :step="0.05"
                      show-input
                      :format-tooltip="value => value.toFixed(2)"
                  />
                </div>
                <div class="config-row">
                  <span class="config-label">缩放比例:</span>
                  <el-slider
                      v-model="singleConfig.scale"
                      :min="0.1"
                      :max="2"
                      :step="0.1"
                      show-input
                      :format-tooltip="value => value.toFixed(2)"
                  />
                </div>
                <!-- 配置建议 -->
                <div class="avatar-config-tip">
                  <el-alert
                      type="info"
                      :closable="false"
                      show-icon
                  >
                    <template #title>配置建议</template>
                    <div>
                      <p>半身人物建议设置: X: 0.0, Y: 0.25, Scale: 1</p>
                      <p>正值向右/向上偏移，负值向左/向下偏移</p>
                      <p>详细配置请参考 <el-link href="https://docs.heygen.com/page/tools" type="primary" target="_blank">HeyGen文档</el-link></p>
                    </div>
                  </el-alert>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-form-item>

        <!-- 语音选择 -->
        <el-form-item
            label="语音"
            prop="voiceId"
            :rules="[{ required: true, message: '请选择语音' }]"
        >
          <div class="select-preview">
            <!-- 现有的语音选择UI -->
            <div v-if="currentVoice" class="preview-content">
              <div class="preview-info">
                <span>{{ currentVoice.name }}</span>
                <div class="preview-tags">
                  <el-tag size="small" type="success">{{ getLanguageLabel(currentVoice.language) }}</el-tag>
                  <el-tag size="small" :type="getGenderType(currentVoice.gender)">
                    {{ getGenderLabel(currentVoice.gender) }}
                  </el-tag>
                </div>
              </div>
              <el-button
                  link
                  type="primary"
                  @click="handlePreviewVoice"
                  :disabled="!currentVoice.previewAudio"
              >试听</el-button>
            </div>
            <el-button @click="showVoiceDialog = true">
              {{ currentVoice ? '更换' : '选择' }}语音
            </el-button>
          </div>
        </el-form-item>

        <!-- 背景配置 -->
        <el-divider content-position="center">背景设置</el-divider>

        <!-- 现有的背景配置UI -->
        <el-form-item label="背景类型" prop="backgroundType">
          <el-radio-group v-model="singleConfig.backgroundType" @change="handleBackgroundTypeChange">
            <el-radio label="color">颜色背景</el-radio>
            <el-radio label="image">图片背景</el-radio>
            <el-radio label="video">视频背景</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 颜色背景设置 -->
        <el-form-item v-if="singleConfig.backgroundType === 'color'" label="背景颜色" prop="backgroundColor">
          <el-color-picker v-model="singleConfig.backgroundColor" />
          <span class="color-value">{{ singleConfig.backgroundColor }}</span>
        </el-form-item>

        <!-- 图片/视频背景设置 -->
        <template v-if="singleConfig.backgroundType === 'image' || singleConfig.backgroundType === 'video'">
          <!-- 现有的背景选择UI -->
          <el-form-item :label="singleConfig.backgroundType === 'image' ? '背景图片' : '背景视频'">
            <!-- 背景预览和选择UI -->
            <div class="form-content-wrapper">
              <div class="background-resource-container">
                <div v-if="singleConfig.backgroundUrl" class="background-preview">
                  <el-image
                      v-if="singleConfig.backgroundType === 'image'"
                      :src="singleConfig.backgroundUrl"
                      class="preview-image"
                      fit="cover"
                  ></el-image>
                  <video
                      v-else
                      :src="singleConfig.backgroundUrl"
                      class="preview-video"
                      autoplay
                      loop
                      muted
                  ></video>
                  <el-button
                      class="remove-btn"
                      type="danger"
                      circle
                      @click="removeBackground('single')"
                      size="small"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>

                <!-- 背景操作按钮 -->
                <div class="background-actions">
                  <el-button type="primary" @click="showBackgroundGallery = true">
                    {{ singleConfig.backgroundUrl ? '更换' : '选择' }}{{ singleConfig.backgroundType === 'image' ? '图片' : '视频' }}
                  </el-button>
                  <el-upload
                      :action="getUploadUrl()"
                      :headers="{ 'Authorization': 'Bearer ' + getToken() }"
                      :on-success="handleUploadSuccess"
                      :on-error="handleUploadError"
                      :before-upload="beforeBackgroundUpload"
                      :on-progress="handleUploadProgress"
                      :show-file-list="false"
                      :accept="singleConfig.backgroundType === 'image' ? 'image/jpeg,image/png' : 'video/mp4,video/webm'"
                      :data="{ fileType: singleConfig.backgroundType }"
                  >
                    <el-button type="primary" :loading="isUploading">
                      {{ isUploading ? '上传中...' : '上传新' + (singleConfig.backgroundType === 'image' ? '图片' : '视频') }}
                    </el-button>
                  </el-upload>
                </div>
              </div>
            </div>
          </el-form-item>

          <!-- 背景适配方式 -->
          <el-form-item label="适配方式" prop="backgroundFit">
            <el-select v-model="singleConfig.backgroundFit" style="width: 120px">
              <el-option label="裁剪" value="crop"></el-option>
              <el-option label="覆盖" value="cover"></el-option>
              <el-option label="包含" value="contain"></el-option>
            </el-select>
          </el-form-item>

          <!-- 视频播放方式 -->
          <el-form-item v-if="singleConfig.backgroundType === 'video'" label="播放方式" prop="backgroundPlayStyle">
            <el-select v-model="singleConfig.backgroundPlayStyle" style="width: 120px">
              <el-option label="循环" value="loop"></el-option>
              <el-option label="单次" value="once"></el-option>
            </el-select>
          </el-form-item>
        </template>

        <!-- 分辨率 -->
        <el-form-item label="分辨率">
          <el-select v-model="singleConfig.resolution" placeholder="选择分辨率" @change="handleResolutionChange('single')" style="width: 120px">
            <el-option label="竖屏" value="1080x1920"></el-option>
            <el-option label="横屏" value="1280x720"></el-option>
          </el-select>
        </el-form-item>

        <!-- 其他选项 -->
        <el-form-item label="其他选项">
          <el-checkbox v-model="singleConfig.isCaption">开启字幕</el-checkbox>
        </el-form-item>
      </el-form>
    </template>

    <!-- 多数字人模式 -->
    <template v-else>
      <!-- 公共配置部分 -->
      <div class="common-settings">
        <h3>公共配置</h3>

        <el-form
            ref="multiFormRef"
            :model="multiConfig"
            label-width="100px"
        >
          <el-form-item label="配置名称" prop="name">
            <el-input v-model="multiConfig.name" placeholder="请输入配置名称" />
          </el-form-item>
          <!-- 背景设置 -->
          <el-form-item label="背景类型">
            <el-radio-group v-model="multiConfig.backgroundType" @change="handleMultiBackgroundTypeChange">
              <el-radio label="color">颜色背景</el-radio>
              <el-radio label="image">图片背景</el-radio>
              <el-radio label="video">视频背景</el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 颜色背景 -->
          <el-form-item v-if="multiConfig.backgroundType === 'color'" label="背景颜色">
            <el-color-picker v-model="multiConfig.backgroundColor" />
            <span class="color-value">{{ multiConfig.backgroundColor }}</span>
          </el-form-item>

          <!-- 图片/视频背景 -->
          <template v-if="multiConfig.backgroundType === 'image' || multiConfig.backgroundType === 'video'">
            <el-form-item :label="multiConfig.backgroundType === 'image' ? '背景图片' : '背景视频'">
              <div class="background-resource-container">
                <div v-if="multiBackgrounds.length === 0" class="empty-background-tip">
                  <el-alert
                      title="请添加至少一个背景"
                      type="info"
                      description="您可以添加多个背景，每个数字人将按顺序使用不同背景。如果背景数量少于数字人数量，背景将循环使用。"
                      :closable="false"
                      show-icon
                  />
                </div>

                <!-- 背景列表 -->
                <div class="background-list">
                  <!-- 已添加的背景 -->
                  <div v-for="(bg, index) in multiBackgrounds" :key="index" class="background-item">
                    <div class="background-preview">
                      <el-image v-if="multiConfig.backgroundType === 'image'" :src="bg.url" class="preview-image" fit="cover"></el-image>
                      <video v-else :src="bg.url" class="preview-video" autoplay loop muted></video>
                      <el-button class="remove-btn" type="danger" circle @click="removeMultiBackgroundItem(index)" size="small">
                        <el-icon><Delete /></el-icon>
                      </el-button>
                    </div>
                    <div class="background-index">背景 #{{ index + 1 }}</div>
                  </div>
                </div>

                <!-- 添加背景按钮区域 - 单独放置 -->
                <div class="background-actions">
                  <el-button type="primary" @click="showMultiBackgroundGallery = true">
                    <el-icon><Plus /></el-icon> 从库中选择背景
                  </el-button>
                  <el-upload
                      :action="getUploadUrl()"
                      :headers="{ 'Authorization': 'Bearer ' + getToken() }"
                      :on-success="handleMultiUploadSuccess"
                      :on-error="handleUploadError"
                      :before-upload="beforeMultiBackgroundUpload"
                      :on-progress="handleUploadProgress"
                      :show-file-list="false"
                      :accept="multiConfig.backgroundType === 'image' ? 'image/jpeg,image/png' : 'video/mp4,video/webm'"
                      :data="{ fileType: multiConfig.backgroundType }"
                  >
                    <el-button type="primary" :loading="isUploading">
                      {{ isUploading ? '上传中...' : '上传' + (multiConfig.backgroundType === 'image' ? '图片' : '视频') }}
                    </el-button>
                  </el-upload>
                </div>
              </div>
            </el-form-item>

            <!-- 背景适配方式 -->
            <el-form-item label="适配方式">
              <el-select v-model="multiConfig.backgroundFit" style="width: 120px">
                <el-option label="裁剪" value="crop"></el-option>
                <el-option label="覆盖" value="cover"></el-option>
                <el-option label="包含" value="contain"></el-option>
              </el-select>
            </el-form-item>

            <!-- 视频播放方式 -->
            <el-form-item v-if="multiConfig.backgroundType === 'video'" label="播放方式">
              <el-select v-model="multiConfig.backgroundPlayStyle" style="width: 120px">
                <el-option label="循环" value="loop"></el-option>
                <el-option label="单次" value="once"></el-option>
              </el-select>
            </el-form-item>
          </template>

          <!-- 分辨率 -->
          <el-form-item label="分辨率">
            <el-select v-model="multiConfig.resolution" placeholder="选择分辨率" @change="handleResolutionChange('multi')" style="width: 120px">
              <el-option label="竖屏" value="1080x1920"></el-option>
              <el-option label="横屏" value="1280x720"></el-option>
            </el-select>
          </el-form-item>

          <!-- 字幕选项 -->
          <el-form-item label="其他选项">
            <el-checkbox v-model="multiConfig.isCaption">开启字幕</el-checkbox>
            <el-checkbox v-model="multiConfig.one_to_one">一对一模式</el-checkbox>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数字人配置列表 -->
      <div class="avatars-container">
        <div class="avatars-header">
          <h3>数字人配置</h3>
          <el-button type="primary" size="small" plain @click="addAvatar" style="float: right;">
            <el-icon><Plus /></el-icon> 添加数字人
          </el-button>
        </div>

        <div v-if="multiConfig.avatarConfigs.length === 0" class="empty-list">
          <el-empty description="请添加至少一个数字人" />
        </div>

        <el-collapse v-else v-model="activeAvatar">
          <el-collapse-item
              v-for="(avatar, index) in multiConfig.avatarConfigs"
              :key="index"
              :name="index"
          >
            <template #title>
              <div class="avatar-title">
                <span>{{ avatar.avatar ? avatar.avatar.avatarName : `数字人 ${index + 1}` }}</span>
              </div>
            </template>

            <el-form label-width="100px">
              <!-- 虚拟人物选择 -->
              <el-form-item label="虚拟人物" required>
                <div class="select-preview">
                  <div v-if="avatar.avatar" class="preview-content">
                    <el-image
                        :src="avatar.avatar.previewImageUrl"
                        class="preview-image"
                        fit="cover"
                    >
                      <template #error>
                        <div class="image-placeholder">
                          <el-icon><Avatar /></el-icon>
                        </div>
                      </template>
                    </el-image>
                    <div class="preview-info">
                      <span>{{ avatar.avatar.avatarName }}</span>
                      <el-space>
                        <el-tag size="small" :type="getGenderType(avatar.avatar.gender)">
                          {{ getGenderLabel(avatar.avatar.gender) }}
                        </el-tag>
                        <el-tag size="small" :type="'danger'">
                          {{avatar.avatar.premium === true ? '高级版' : '基础版'}}
                        </el-tag>
                      </el-space>
                    </div>
                    <div class="avatar-actions" style="text-align: center">
                      <el-button
                          type="primary"
                          link
                          size="small"
                          @click="previewMultiAvatar(avatar.avatar)"
                      >
                        <el-icon><VideoPlay /></el-icon>预览
                      </el-button>
                    </div>
                  </div>
                  <el-button @click="() => openAvatarSelector(index)">
                    {{ avatar.avatar ? '更换' : '选择' }}虚拟人物
                  </el-button>
                </div>
              </el-form-item>

              <!-- 人物配置 -->
              <el-form-item label="人物配置">
                <el-collapse>
                  <el-collapse-item title="详细配置">
                    <div class="avatar-config-form">
                      <div class="config-row">
                        <span class="config-label">水平偏移 (X):</span>
                        <el-slider
                            v-model="avatar.xOffset"
                            :min="-1"
                            :max="1"
                            :step="0.05"
                            show-input
                            :format-tooltip="value => value.toFixed(2)"
                        />
                      </div>
                      <div class="config-row">
                        <span class="config-label">垂直偏移 (Y):</span>
                        <el-slider
                            v-model="avatar.yOffset"
                            :min="-1"
                            :max="1"
                            :step="0.05"
                            show-input
                            :format-tooltip="value => value.toFixed(2)"
                        />
                      </div>
                      <div class="config-row">
                        <span class="config-label">缩放比例:</span>
                        <el-slider
                            v-model="avatar.scale"
                            :min="0.1"
                            :max="2"
                            :step="0.1"
                            show-input
                            :format-tooltip="value => value.toFixed(2)"
                        />
                      </div>
                    </div>
                  </el-collapse-item>
                </el-collapse>
              </el-form-item>

              <!-- 语音选择 -->
              <el-form-item label="语音" required>
                <div class="select-preview">
                  <div v-if="avatar.voice" class="preview-content">
                    <div class="preview-info">
                      <span>{{ avatar.voice.name }}</span>
                      <div class="preview-tags">
                        <el-tag size="small" type="success">{{ getLanguageLabel(avatar.voice.language) }}</el-tag>
                        <el-tag size="small" :type="getGenderType(avatar.voice.gender)">
                          {{ getGenderLabel(avatar.voice.gender) }}
                        </el-tag>
                      </div>
                    </div>
                    <el-button
                        link
                        type="primary"
                        @click="previewAvatarVoice(avatar.voice)"
                        :disabled="!avatar.voice.previewAudio"
                    >试听</el-button>
                  </div>
                  <el-button @click="() => openVoiceSelector(index)">
                    {{ avatar.voice ? '更换' : '选择' }}语音
                  </el-button>
                </div>
              </el-form-item>

              <!-- 操作按钮 -->
              <el-form-item>
                <el-button type="danger" @click="removeAvatar(index)" plain size="small">
                  <el-icon><Delete /></el-icon> 删除此数字人
                </el-button>
              </el-form-item>
            </el-form>
          </el-collapse-item>
        </el-collapse>
      </div>
    </template>

    <!-- 弹窗底部按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 虚拟人物选择弹窗 -->
  <el-dialog
      v-model="showAvatarDialog"
      title="选择虚拟人物"
      width="900px"
      append-to-body
  >
    <AvatarList @select="handleAvatarSelect" />
  </el-dialog>

  <!-- 多数字人虚拟人物选择弹窗 -->
  <el-dialog
      v-model="showMultiAvatarDialog"
      title="选择虚拟人物"
      width="900px"
      append-to-body
  >
    <AvatarList @select="handleMultiAvatarSelect" />
  </el-dialog>

  <!-- 语音选择弹窗 -->
  <el-dialog
      v-model="showVoiceDialog"
      title="选择语音"
      width="900px"
      append-to-body
  >
    <VoiceList @select="handleVoiceSelect" />
  </el-dialog>

  <!-- 多数字人语音选择弹窗 -->
  <el-dialog
      v-model="showMultiVoiceDialog"
      title="选择语音"
      width="900px"
      append-to-body
  >
    <VoiceList @select="handleMultiVoiceSelect" />
  </el-dialog>

  <!-- 背景资源库选择弹窗 -->
  <el-dialog
      v-model="showBackgroundGallery"
      :title="singleConfig.backgroundType === 'image' ? '选择背景图片' : '选择背景视频'"
      width="900px"
      append-to-body
  >
    <BackgroundGallery
        :type="singleConfig.backgroundType"
        @select="handleBackgroundSelect"
    />
  </el-dialog>

  <!-- 多数字人背景资源库选择弹窗 -->
  <el-dialog
      v-model="showMultiBackgroundGallery"
      :title="multiConfig.backgroundType === 'image' ? '选择背景图片' : '选择背景视频'"
      width="900px"
      append-to-body
  >
    <BackgroundGallery
        :type="multiConfig.backgroundType"
        @select="handleMultiBackgroundSelect"
    />
  </el-dialog>

  <!-- 音频播放器 -->
  <audio
      ref="audioPlayer"
      @ended="handleAudioEnd"
      style="display: none"
  ></audio>

  <!-- 预览弹窗 -->
  <el-dialog
      v-model="previewDialog.visible"
      title="虚拟人物预览"
      width="630"
      :close-on-click-modal="false"
  >
    <video
        width="600"
        v-if="previewDialog.videoUrl"
        :src="previewDialog.videoUrl"
        controls
        class="preview-video"
    ></video>
  </el-dialog>
</template>

<script setup>
import {computed, nextTick, onMounted, ref, watch} from 'vue'
import {Avatar, Delete, InfoFilled, Plus, VideoPlay} from '@element-plus/icons-vue'
import {ElMessage} from 'element-plus'
import AvatarList from '@/components/AvatarSelect.vue'
import VoiceList from '@/components/VoiceSelect.vue'
import BackgroundGallery from '@/components/BackgroundGallery.vue'
import {getGenderLabel, getGenderType, getLanguageLabel} from '@/utils/label'
import {getToken} from '@/utils/auth'
import {getUploadUrl} from '@/utils/uploadConfig'
import {useAvatarStore} from '@/stores/video/avatar'
import {useVoiceStore} from '@/stores/video/voice'
import { useBackgroundStore } from '@/stores/video/background'
import { useConfigStore } from '@/stores/video/config.js'

// 多背景管理
const multiBackgrounds = ref([]);

const avatarStore = useAvatarStore()
const voiceStore = useVoiceStore()
const backgroundStore = useBackgroundStore()

// 属性定义
const props = defineProps({
  visible: Boolean,
  title: String,
  defaultConfig: Object,
  submitting: Boolean,
  article: Object // 文章内容，用于多数字人场景
})

// 事件定义
const emit = defineEmits(['update:visible', 'confirm'])

// 响应式数据
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

// 配置模式
const configMode = ref('single')

// 单数字人配置表单
const singleFormRef = ref(null)
const currentAvatar = ref(null)
const currentVoice = ref(null)

// 单数字人配置
const singleConfig = ref({
  name: '',
  avatarId: '',
  voiceId: '',
  // 人物配置
  xOffset: 0.03,
  yOffset: 0.13,
  scale: 1.4,
  // 背景相关属性
  backgroundType: 'color',
  backgroundId: '',
  backgroundColor: '#f6f6fc',
  backgroundUrl: '',
  backgroundFit: 'crop',
  backgroundPlayStyle: 'loop',
  width: 1080,
  height: 1920,
  isDefault: false,
  isCaption: false,
  resolution: '1080x1920'
})

// 多数字人配置
const multiFormRef = ref(null)
const activeAvatar = ref(['0']) // 默认展开第一个数字人配置
const multiConfig = ref({
  name: '',
  // 背景相关属性
  backgroundType: 'color',
  backgroundId: '',
  backgroundUrl: '',
  backgroundUrls: [],
  backgroundIds: [],
  backgroundColor: '#f6f6fc',
  backgroundFit: 'crop',
  backgroundPlayStyle: 'loop',
  width: 1080,
  height: 1920,
  isCaption: false,
  one_to_one: false,
  resolution: '1080x1920',
  // 数字人配置列表
  avatarConfigs: []
})

// 控制弹窗显示
const showAvatarDialog = ref(false)
const showVoiceDialog = ref(false)
const showBackgroundGallery = ref(false)
const showMultiAvatarDialog = ref(false)
const showMultiVoiceDialog = ref(false)
const showMultiBackgroundGallery = ref(false)

// 预览弹窗
const previewDialog = ref({
  visible: false,
  videoUrl: ''
})

// 当前操作的数字人索引
const currentAvatarIndex = ref(0)

// 上传相关状态
const isUploading = ref(false)
const uploadProgress = ref(0)
const audioPlayer = ref(null)

// 验证规则
const rules = {
  name: [
    { required: true, message: '请输入配置名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  avatarId: [
    { required: true, message: '请选择虚拟人物', trigger: 'change' }
  ],
  voiceId: [
    { required: true, message: '请选择语音', trigger: 'change' }
  ]
}

// 上传失败处理
const handleUploadError = (error) => {
  console.error('上传失败:', error)
  ElMessage.error('上传失败，请稍后重试')
}

// 初始化
onMounted(() => {
  if (props.defaultConfig) {
    // 如果有默认配置，初始化表单
    initFromDefaultConfig()
  } else if (props.article && props.article.content) {
    // 如果有文章内容，自动切换到多数字人模式
    configMode.value = 'multiple'
    // 添加一个默认的数字人配置
    addAvatar()
  }
})

// 监听 props.defaultConfig 变化
watch(() => props.defaultConfig, (newConfig) => {
  if (newConfig) {
    initFromDefaultConfig()
  }
}, { immediate: true })

// 从默认配置初始化表单
const initFromDefaultConfig = () => {

  const config = props.defaultConfig
  if (!config) return

  if (config.configType === 'multiple') {
    // 多数字人模式
    configMode.value = 'multiple'

    // 设置名称
    multiConfig.value.name = config.name || ''

    console.log(config.commonConfig)
    // 初始化公共配置
    if (config.commonConfig) {
      const commonConfig = config.commonConfig
      multiConfig.value.backgroundType = commonConfig.backgroundType || 'color'
      multiConfig.value.backgroundId = commonConfig.backgroundId || ''
      multiConfig.value.backgroundUrl = commonConfig.backgroundUrl || ''
      multiConfig.value.backgroundUrls = commonConfig.backgroundUrls || []
      multiConfig.value.backgroundIds = commonConfig.backgroundIds || []
      multiConfig.value.backgroundColor = commonConfig.backgroundColor || '#f6f6fc'
      multiConfig.value.backgroundFit = commonConfig.backgroundFit || 'cover'
      multiConfig.value.backgroundPlayStyle = commonConfig.backgroundPlayStyle || 'loop'
      multiConfig.value.width = commonConfig.width || 1080
      multiConfig.value.height = commonConfig.height || 1920
      multiConfig.value.isCaption = commonConfig.isCaption || false
      multiConfig.value.one_to_one = commonConfig.one_to_one || false
      multiConfig.value.resolution = `${commonConfig.width || 1080}x${commonConfig.height || 1920}`
    }

    // 清空现有数字人配置
    multiConfig.value.avatarConfigs = []

    // 初始化数字人配置列表
    if (config.avatarConfigs && config.avatarConfigs.length > 0) {
      // 使用map创建新数组避免引用问题
      multiConfig.value.avatarConfigs = config.avatarConfigs.map(avatarConfig => ({
        avatarId: avatarConfig.avatarId || '',
        voiceId: avatarConfig.voiceId || '',
        xOffset: avatarConfig.xOffset !== undefined ? avatarConfig.xOffset : 0.03,
        yOffset: avatarConfig.yOffset !== undefined ? avatarConfig.yOffset : 0.13,
        scale: avatarConfig.scale !== undefined ? avatarConfig.scale : 1.40,
        avatar: avatarConfig.avatar || null,
        voice: avatarConfig.voice || null
      }))

      initMultiBackgrounds(config.commonConfig)

    } else {
      // 没有数字人配置，添加一个默认的
      addAvatar()
    }
  } else {
    // 单数字人模式
    configMode.value = 'single'

    // 初始化单数字人配置
    singleConfig.value = {
      ...singleConfig.value,
      ...config.config,
      resolution: `${config.config.width}x${config.config.height}`
    }

    // 加载虚拟人物信息
    if (config.config.avatarId) {
      loadAvatarInfo(config.config.avatarId).then(avatar => {
        currentAvatar.value = avatar
      })
    }

    // 加载语音信息
    if (config.config.voiceId) {
      loadVoiceInfo(config.config.voiceId).then(voice => {
        currentVoice.value = voice
      })
    }
  }
}

// 加载虚拟人物信息
const loadAvatarInfo = async (avatarId) => {
  try {
    const response = await avatarStore.fetchById(avatarId)
    const data = await response.json()
    if (data.code === 200 && data.data) {
      return data.data
    }
    return null
  } catch (error) {
    console.error('加载虚拟人物信息失败:', error)
    return null
  }
}

// 加载语音信息
const loadVoiceInfo = async (voiceId) => {
  try {
    const response = await voiceStore.fetchVoiceById(voiceId)
    const data = await response.json()
    if (data.code === 200 && data.data) {
      return data.data
    }
    return null
  } catch (error) {
    console.error('加载语音信息失败:', error)
    return null
  }
}

// 添加数字人配置
const addAvatar = () => {
  multiConfig.value.avatarConfigs.push({
    avatarId: '',
    voiceId: '',
    avatar: null,
    voice: null,
    xOffset: 0.03,
    yOffset: 0.13,
    scale: 1.4
  })

  // 自动展开新添加的数字人配置
  nextTick(() => {
    activeAvatar.value = [(multiConfig.value.avatarConfigs.length - 1).toString()]
  })
}

// 删除数字人配置
const removeAvatar = (index) => {
  multiConfig.value.avatarConfigs.splice(index, 1)

  // 如果删除后没有数字人配置，添加一个默认的
  if (multiConfig.value.avatarConfigs.length === 0) {
    addAvatar()
  }
}

// 打开多数字人配置中的虚拟人物选择器
const openAvatarSelector = (index) => {
  currentAvatarIndex.value = index
  showMultiAvatarDialog.value = true
}

// 打开多数字人配置中的语音选择器
const openVoiceSelector = (index) => {
  currentAvatarIndex.value = index
  showMultiVoiceDialog.value = true
}

// 模式切换处理
const handleModeChange = (mode) => {
  // 从单数字人切换到多数字人时，如果没有数字人配置，添加一个默认的
  if (mode === 'multiple' && multiConfig.value.avatarConfigs.length === 0) {
    addAvatar()
  }
}

// 处理背景类型变化（单数字人模式）
const handleBackgroundTypeChange = (type) => {
  // 清空之前的背景设置
  if (type === 'color') {
    singleConfig.value.backgroundUrl = ''
    singleConfig.value.backgroundId = ''
  } else if (type === 'image' || type === 'video') {
    singleConfig.value.backgroundColor = ''
  }
}

// 处理背景类型变化（多数字人模式）
const handleMultiBackgroundTypeChange = (type) => {
  // 清空之前的背景设置
  if (type === 'color') {
    multiConfig.value.backgroundUrl = ''
    multiConfig.value.backgroundId = ''
  } else if (type === 'image' || type === 'video') {
    multiConfig.value.backgroundColor = ''
  }
}

// 移除背景
const removeBackground = (mode) => {
  if (mode === 'single') {
    singleConfig.value.backgroundUrl = ''
    singleConfig.value.backgroundId = ''
  } else {
    multiConfig.value.backgroundUrl = ''
    multiConfig.value.backgroundId = ''
  }
}

// 处理分辨率变化
const handleResolutionChange = (mode, value) => {
  const resolution = mode === 'single' ? singleConfig.value.resolution : multiConfig.value.resolution
  const [width, height] = resolution.split('x').map(Number)

  if (mode === 'single') {
    singleConfig.value.width = width
    singleConfig.value.height = height
  } else {
    multiConfig.value.width = width
    multiConfig.value.height = height
  }
}

// 单数字人模式下的虚拟人物选择
const handleAvatarSelect = (avatar) => {
  currentAvatar.value = avatar
  singleConfig.value.avatarId = avatar.avatarId
  showAvatarDialog.value = false
}

// 多数字人模式下的虚拟人物选择
const handleMultiAvatarSelect = (avatar) => {
  const index = currentAvatarIndex.value
  multiConfig.value.avatarConfigs[index].avatar = avatar
  multiConfig.value.avatarConfigs[index].avatarId = avatar.avatarId
  showMultiAvatarDialog.value = false
}

// 单数字人模式下的语音选择
const handleVoiceSelect = (voice) => {
  currentVoice.value = voice
  singleConfig.value.voiceId = voice.voiceId
  showVoiceDialog.value = false
}

// 多数字人模式下的语音选择
const handleMultiVoiceSelect = (voice) => {
  const index = currentAvatarIndex.value
  multiConfig.value.avatarConfigs[index].voice = voice
  multiConfig.value.avatarConfigs[index].voiceId = voice.voiceId
  showMultiVoiceDialog.value = false
}

// 单数字人模式下的背景选择
const handleBackgroundSelect = (background) => {
  singleConfig.value.backgroundUrl = background.url
  singleConfig.value.backgroundId = background.id
  showBackgroundGallery.value = false
}

// 处理多背景选择
const handleMultiBackgroundSelect = (background) => {
  multiBackgrounds.value.push({
    id: background.id,
    url: background.url
  });
  updateMultiBackgroundUrls(); // 更新公共配置中的背景列表
  showMultiBackgroundGallery.value = false;
}

// 上传进度处理
const handleUploadProgress = (event) => {
  isUploading.value = true
  if (event.total > 0) {
    uploadProgress.value = Math.round((event.loaded / event.total) * 100)
  }
}

// 单数字人模式下的背景上传前验证
const beforeBackgroundUpload = (file) => {
  return validateUpload(file, singleConfig.value.backgroundType)
}

// 多数字人模式下的背景上传前验证
const beforeMultiBackgroundUpload = (file) => {
  return validateUpload(file, multiConfig.value.backgroundType)
}

// 验证上传文件
const validateUpload = (file, backgroundType) => {
  // 重置上传状态
  isUploading.value = true
  uploadProgress.value = 0

  // 允许的MIME类型
  const allowedImageTypes = ['image/jpeg', 'image/png']
  const allowedVideoTypes = ['video/mp4', 'video/webm']

  // 根据背景类型验证文件类型
  if (backgroundType === 'image') {
    if (!allowedImageTypes.includes(file.type)) {
      isUploading.value = false
      ElMessage.error('背景图片只能是 JPG 或 PNG 格式!')
      return false
    }
  } else if (backgroundType === 'video') {
    if (!allowedVideoTypes.includes(file.type)) {
      isUploading.value = false
      ElMessage.error('背景视频只能是 MP4 或 WEBM 格式!')
      return false
    }
  }

  // 文件大小验证 (50MB)
  const maxSize = 50 * 1024 * 1024
  if (file.size > maxSize) {
    isUploading.value = false
    ElMessage.error('文件大小不能超过 50MB!')
    return false
  }

  return true
}

// 单数字人模式下的上传成功处理
const handleUploadSuccess = (response) => {
  isUploading.value = false
  uploadProgress.value = 100

  if (response.code === 200 && response.data) {
    singleConfig.value.backgroundUrl = response.data.url
    singleConfig.value.backgroundId = response.data.id
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(response.message || '上传失败')
  }
}

// 上传多背景成功处理
const handleMultiUploadSuccess = (response) => {
  isUploading.value = false;
  uploadProgress.value = 100;

  if (response.code === 200 && response.data) {
    // 添加到多背景列表
    multiBackgrounds.value.push({
      id: response.data.id,
      url: response.data.url
    });
    updateMultiBackgroundUrls(); // 更新公共配置中的背景列表

    // 刷新背景资源库数据
    backgroundStore.getBackgrounds({
      page: 1,
      pageSize: 12,
      type: multiConfig.value.backgroundType
    });

    ElMessage.success('上传成功');
  } else {
    ElMessage.error(response.message || '上传失败');
  }
}

// 移除特定背景项
const removeMultiBackgroundItem = (index) => {
  multiBackgrounds.value.splice(index, 1);
  updateMultiBackgroundUrls(); // 更新公共配置中的背景列表
}

// 更新公共配置中的背景列表
const updateMultiBackgroundUrls = () => {
  // 将多背景信息更新到配置对象中
  multiConfig.value.backgroundUrls = multiBackgrounds.value.map(bg => bg.url);
  multiConfig.value.backgroundIds = multiBackgrounds.value.map(bg => bg.id);

  // 如果有背景，同时更新单一背景字段用于兼容
  if (multiBackgrounds.value.length > 0) {
    multiConfig.value.backgroundUrl = multiBackgrounds.value[0].url;
    multiConfig.value.backgroundId = multiBackgrounds.value[0].id;
  } else {
    multiConfig.value.backgroundUrl = '';
    multiConfig.value.backgroundId = '';
  }
}

// 从多配置初始化多背景列表
const initMultiBackgrounds = (config) => {
  multiBackgrounds.value = [];

  if (config.backgroundUrls && config.backgroundUrls.length > 0) {
    // 从配置中加载多背景
    config.backgroundUrls.forEach((url, index) => {
      const id = config.backgroundIds && index < config.backgroundIds.length
          ? config.backgroundIds[index]
          : '';

      multiBackgrounds.value.push({
        id: id,
        url: url
      });
    });
  } else if (config.backgroundUrl) {
    // 兼容旧版，从单一背景转换
    multiBackgrounds.value.push({
      id: config.backgroundId || '',
      url: config.backgroundUrl
    });
  }
}

// 虚拟人物预览
const handlePreview = (avatar) => {
  if (!avatar || !avatar.previewVideoUrl) {
    ElMessage.warning('预览视频不可用')
    return
  }

  previewDialog.value.videoUrl = avatar.previewVideoUrl
  previewDialog.value.visible = true
}

// 多数字人模式下的虚拟人物预览
const previewMultiAvatar = (avatar) => {
  if (!avatar || !avatar.previewVideoUrl) {
    ElMessage.warning('预览视频不可用')
    return
  }

  previewDialog.value.videoUrl = avatar.previewVideoUrl
  previewDialog.value.visible = true
}

// 语音预览
const handlePreviewVoice = async () => {
  if (!currentVoice.value?.previewAudio) {
    ElMessage.warning('试听音频不可用')
    return
  }

  try {
    audioPlayer.value.src = currentVoice.value.previewAudio
    await audioPlayer.value.play()
  } catch (error) {
    console.error('音频播放失败:', error)
    ElMessage.error('音频播放失败')
  }
}

// 多数字人模式下的语音预览
const previewAvatarVoice = async (voice) => {
  if (!voice?.previewAudio) {
    ElMessage.warning('试听音频不可用')
    return
  }

  try {
    audioPlayer.value.src = voice.previewAudio
    await audioPlayer.value.play()
  } catch (error) {
    console.error('音频播放失败:', error)
    ElMessage.error('音频播放失败')
  }
}

// 音频播放结束
const handleAudioEnd = () => {
  if (audioPlayer.value) {
    audioPlayer.value.src = ''
  }
}

// 验证多数字人配置
const validateMultiConfig = () => {
  if (multiConfig.value.avatarConfigs.length === 0) {
    ElMessage.warning('请至少添加一个数字人')
    return false
  }

  for (let i = 0; i < multiConfig.value.avatarConfigs.length; i++) {
    const config = multiConfig.value.avatarConfigs[i]
    if (!config.avatarId) {
      ElMessage.warning(`第 ${i + 1} 个数字人未选择虚拟人物`)
      return false
    }

    if (!config.voiceId) {
      ElMessage.warning(`第 ${i + 1} 个数字人未选择语音`)
      return false
    }
  }

  return true
}

// 提交配置
const handleSubmit = async () => {
  if (configMode.value === 'single') {
    // 单数字人模式提交
    if (!singleFormRef.value) return

    try {
      await singleFormRef.value.validate()

      const singleResult = {
        mode: 'single',
        config: {
          id: singleConfig.value.id,
          name: singleConfig.value.name,
          avatarId: singleConfig.value.avatarId,
          voiceId: singleConfig.value.voiceId,
          xOffset: singleConfig.value.xOffset,
          yOffset: singleConfig.value.yOffset,
          scale: singleConfig.value.scale,
          backgroundType: singleConfig.value.backgroundType,
          backgroundId: singleConfig.value.backgroundId,
          backgroundColor: singleConfig.value.backgroundColor,
          backgroundUrl: singleConfig.value.backgroundUrl,
          backgroundFit: singleConfig.value.backgroundFit,
          backgroundPlayStyle: singleConfig.value.backgroundPlayStyle,
          width: singleConfig.value.width,
          height: singleConfig.value.height,
          isDefault: singleConfig.value.isDefault,
          isCaption: singleConfig.value.isCaption
        }
      }

      emit('confirm', singleResult)
      dialogVisible.value = false
    } catch (error) {
      console.error('表单验证失败:', error)
    }
  } else {
    // 多数字人模式提交
    if (!validateMultiConfig()) return

    // 确保背景列表已同步到配置
    updateMultiBackgroundUrls();

    // 构建结果对象
    const multiResult = {
      mode: 'multiple',
      name: multiConfig.value.name,
      commonConfig: {
        backgroundType: multiConfig.value.backgroundType,
        backgroundId: multiConfig.value.backgroundId,
        backgroundUrl: multiConfig.value.backgroundUrl,
        backgroundUrls: multiConfig.value.backgroundUrls,
        backgroundIds: multiConfig.value.backgroundIds,
        backgroundColor: multiConfig.value.backgroundColor,
        backgroundFit: multiConfig.value.backgroundFit,
        backgroundPlayStyle: multiConfig.value.backgroundPlayStyle,
        width: multiConfig.value.width,
        height: multiConfig.value.height,
        isCaption: multiConfig.value.isCaption,
        one_to_one: multiConfig.value.one_to_one
      },
      avatarConfigs: multiConfig.value.avatarConfigs.map(config => ({
        avatarId: config.avatarId,
        voiceId: config.voiceId,
        xOffset: config.xOffset,
        yOffset: config.yOffset,
        scale: config.scale
      }))
    }

    emit('confirm', multiResult)
    dialogVisible.value = false
  }
}
</script>

<style scoped>
.form-content-wrapper {
  width: 100%;
  display: block;
}

/* 背景资源容器 */
.background-resource-container {
  width: 100%;
}

/* 背景图片列表容器 */
.background-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); /* 自适应列数，最小宽度160px */
  gap: 15px;
  width: 100%;
  margin-bottom: 20px;
}

/* 背景图片项 */
.background-item {
  position: relative;
  width: 100%; /* 使用100%宽度填充网格单元格 */
}

/* 背景预览容器 */
.background-item .background-preview,
.background-preview {
  position: relative;
  width: 100%;
  height: 0;
  padding-bottom: 56.25%; /* 16:9比例 */
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid #e4e7ed;
}

/* 背景图片和视频 */
.background-item .background-preview .preview-image,
.background-item .background-preview .preview-video,
.background-preview .preview-image,
.background-preview .preview-video {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 背景索引标签 */
.background-index {
  text-align: center;
  margin-top: 8px;
  font-size: 14px;
  color: #606266;
}

/* 删除按钮 */
.background-item .remove-btn,
.remove-btn {
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 10;
  opacity: 0.9;
}

/* 背景操作按钮区域 */
.background-actions {
  display: flex;
  gap: 12px;
  margin-top: 15px;
  flex-wrap: wrap;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .background-list {
    grid-template-columns: repeat(2, 1fr); /* 中等屏幕显示2个 */
  }
}

@media screen and (max-width: 576px) {
  .background-list {
    grid-template-columns: 1fr; /* 小屏幕显示1个 */
  }
}

/* 上传图片按钮样式 */
.background-actions .el-button {
  flex: 1;
  min-width: 120px;
  max-width: 200px;
}

/* 从库选择背景按钮 */
.background-actions .el-button:first-child {
  flex: 2;
}

/* 单个背景预览（非列表项内的）*/
.background-preview:not(.background-item .background-preview) {
  max-width: 320px;
}

/* 其他样式补充，保持与整体风格一致 */
.mode-selector {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16px;
}

.select-preview {
  display: flex;
  align-items: center;
  gap: 15px;
}

.preview-content {
  display: flex;
  align-items: center;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
  background-color: #f5f7fa;
  flex: 1;
}

.preview-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  object-fit: cover;
}

.preview-info {
  display: flex;
  flex-direction: column;
  margin-left: 10px;
  flex: 1;
}

.avatar-config-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.config-row {
  display: flex;
  align-items: center;
}

.config-label {
  width: 120px;
  font-size: 14px;
  color: #606266;
}

.avatars-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.mb-4 {
  margin-bottom: 16px;
}

.ml-2 {
  margin-left: 8px;
}
</style>